﻿using System;
using AutoMapper;
using ORS.OrderRobot.Domain;
using ORS.OrderRobot.IOC;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;

namespace ORS.OrderRobot.Service
{
	public class AccountOrderService: IAccountOrderService,IScoped
    {
        private readonly IMapper _mapper;
        private readonly IOrderRepository _accountOrderRepository;
        private readonly IProductMointerLogService _productMointerLogService;
        public AccountOrderService(
            IMapper mapper,
            IOrderRepository accountOrderRepository,
            IProductMointerLogService productMointerLogService
        )
		{
            _accountOrderRepository = accountOrderRepository;
            _productMointerLogService = productMointerLogService;
            _mapper = mapper;
		}

        public async Task<List<OrderDto>> GetList(GetOrderInput input)
        {
           var sorting = new List<SortingRequest> {
           new()
               {
                   SortField = "id",
                   IsAscending = false,
               }
            };
            var accountOrder = await _accountOrderRepository.GetListBySortAsync(sortingRequests: sorting, includeDetails: true);
            var productIds = accountOrder.Select(x => x.ProductId).ToArray();
            var productList = await _productMointerLogService.GetList(new GetProductInput { ProductIds = productIds });
            var dtos = _mapper.Map<List<OrderDto>>(accountOrder);
            foreach (var dto in dtos)
            {
                var product = productList.FirstOrDefault(x => x.ProductId == dto.ProductId);
                dto.ProductName = product?.ProductName;
            }
            return dtos;
        }
    }
}

